<template>
	<div class="main-wrapper">
		<el-form ref="formRef" :model="tableInfo" :rules="tableNameRules" label-width="auto">
			<el-form-item label="表名" prop="name">
				<template #label>
					<div>
						<span>表名</span>
						<el-tooltip class="box-item" effect="dark" :content="tableNameTooltipContent" placement="bottom-end">
							<el-icon style="vertical-align: middle;">
								<InfoFilled />
							</el-icon>
						</el-tooltip>
					</div>
				</template>
				<el-icon style="position: absolute;left: 0;top: 0;">
					<InfoFilled />
				</el-icon>
				<el-input v-model="tableInfo.name" maxlength="192" />
			</el-form-item>
		</el-form>
		<!-- 子表创建 -->
		<div v-if="props.type == 3">
			<div style="margin-bottom: 6px;">标签值</div>
			<el-scrollbar max-height="400px">
				<div class="column-tag-config-wrapper">
					<el-row class="row-class" v-for="(item,index) in childTableTags" :key="index">
					<el-col :span="12">
						<el-input v-model="item.showInfo" disabled/>
					</el-col>
					<el-col :span="12">
						<el-input v-if="!item.isNumber" v-model="item.value"/>
						<el-input-number style="width: 100%;" v-else v-model="item.value"/>
					</el-col>
				</el-row>
				</div>
			</el-scrollbar>
		</div>
		<!-- 列 超级表 普通表会用到 -->
		<div v-if="props.type != 3">
			<div style="margin-bottom: 6px;">列</div>
			<el-scrollbar :max-height="columnMaxHeight">
				<div class="column-tag-config-wrapper">
					<!-- 列配置 -->
					<el-row class="row-class" v-for="(item, index) in tableInfo.columnsInfo" :key="index">
						<el-col :span="6">
							<el-select class="max-width" :disabled="index == 0" v-model="item.type" placeholder="数据类型"
								:title="item.type" @change="updateRelevantData(index, true)">
								<el-option v-for="item in columnDataTypeOption" :key="item.name" :label="item.name"
									:value="item.name" />
							</el-select>
						</el-col>
						<el-col :span="6" v-show="item.isLength">
							<el-input-number class="max-width" placeholder="长度" v-model="item.length" :min="1" :max="100000" />
						</el-col>
						<el-col :span="getInputSpan(item.type)" style="padding-right:2px;">
							<el-input v-model="item.name" placeholder="列名" />
						</el-col>
						<el-col :span="2">
							<div class="button">
								<el-button :disabled="index == 0" @click="deleteColumn(index)">
									<el-icon>
										<Minus />
									</el-icon>
								</el-button>
							</div>
						</el-col>
						<el-col :span="2">
							<div class="button">
								<el-button @click="addColumn(index)">
									<el-icon>
										<Plus />
									</el-icon>
								</el-button>
							</div>
						</el-col>
					</el-row>
				</div>
			</el-scrollbar>
		</div>
		<!-- 标签 超级表会用到 -->
		<div v-if="props.type == 1">
			<div style="margin: 6px 0;">标签</div>
			<el-scrollbar max-height="140px">
				<div class="column-tag-config-wrapper">
					<!-- 标签配置 -->
					<el-row class="row-class" v-for="(item, index) in tableInfo.tagsInfo" :key="index">
						<el-col :span="6">
							<el-select class="max-width" v-model="item.type" placeholder="数据类型" :title="item.type"
								@change="updateRelevantData(index, false)">
								<el-option v-for="item in dataTypeOptions" :key="item.name" :label="item.name" :value="item.name" />
							</el-select>
						</el-col>
						<el-col :span="6" v-show="item.isLength">
							<el-input-number class="max-width" placeholder="长度" v-model="item.length" :min="1" :max="100000" />
						</el-col>
						<el-col :span="getInputSpan(item.type)" style="padding-right:2px;">
							<el-input v-model="item.name" placeholder="列名" />
						</el-col>
						<el-col :span="2">
							<div class="button">
								<el-button :disabled="index == 0" @click="deleteTag(index)">
									<el-icon>
										<Minus />
									</el-icon>
								</el-button>
							</div>
						</el-col>
						<el-col :span="2">
							<div class="button">
								<el-button @click="addTag(index)">
									<el-icon>
										<Plus />
									</el-icon>
								</el-button>
							</div>
						</el-col>
					</el-row>
				</div>
			</el-scrollbar>
		</div>
	</div>
</template>
<script lang="js" setup>
/**
 * 注意：TDEngine创建表格第一个是时间戳
 * 超级表中列的最大个数为 4096，需要注意，这里的 4096 是包含 TAG 列在内的，最小个数为 3，包含一个时间戳主键、一个 TAG 列和一个数据列。
	 除时间戳主键列之外，还可以通过 PRIMARY KEY 关键字指定第二列为额外的主键列。被指定为主键列的第二列必须为整型或字符串类型（varchar）
	 TAGS语法指定超级表的标签列，标签列需要遵循以下约定：
	 TAGS 中的 TIMESTAMP 列写入数据时需要提供给定值，而暂不支持四则运算，例如 NOW + 10s 这类表达式。
	 TAGS 列名不能与其他列名相同。
	 TAGS 列名不能为预留关键字。
	 TAGS 最多允许 128 个，至少 1 个，总长度不超过 16 KB。
	 关于 ENCODE 和 COMPRESS 的使用，请参考 按列压缩
	 关于 table_option 中的参数说明，请参考 建表 SQL 说明
 */
import { ref, onMounted, watch, computed } from 'vue'
//TDEngine3.0 支持的数据类型
import { TDENGINE_DATA_TYPES,getTypeByName } from '../../utils/global';
/**
 * 数据初始化
 */
const props = defineProps({
	type: Number,
	visiable: Boolean,
	superTableInfo: Object
})
//用于表单验证
const formRef = ref(null)

//用来存储子表的建表信息
const childTableTags = ref([])

watch(() => props.visiable, (newval) => {
	if (!newval) {
		tableInfo.value.name = ''
		let initColumn = JSON.parse(JSON.stringify(columnOrTagTemplate))
		initColumn.type = "TIMESTAMP"
		tableInfo.value.columnsInfo = [initColumn];
		tableInfo.value.tagsInfo = [JSON.parse(JSON.stringify(columnOrTagTemplate))]
		if(formRef){
			formRef.value.clearValidate();
		}
	}
})
watch(()=>props.superTableInfo,(newVal)=>{
	let tagsInfo = newVal.tagsInfo;
	childTableTags.value = [];
	for(let i=0;i<tagsInfo.length;i++){
		let obj = {};
		obj.name = tagsInfo[i].name;
		obj.showInfo = tagsInfo[i].name+":"+tagsInfo[i].type;
		obj.isNumber = getTypeByName(tagsInfo[i].type).isNumber;
		obj.isNumber ? obj.value = 0 : obj.value= "";
		obj.type = tagsInfo[i].type;
		childTableTags.value.push(obj);
	}
})


const columnMaxHeight = computed(() => {
	if (props.type == 1) {
		return '140px';
	} else {
		return '300px'
	}
})

//数据类型选项
const dataTypeOptions = ref(null);
onMounted(() => {
	dataTypeOptions.value = JSON.parse(JSON.stringify(TDENGINE_DATA_TYPES));
})

const columnDataTypeOption = computed(() => {
	return JSON.parse(JSON.stringify(TDENGINE_DATA_TYPES)).filter(item => item.name != "JSON");
})

const tableNameTooltipContent = "表名只能由字母、数字和下划线组成，且不能以数字开头。默认不区分大小写，如果要创建区分大小写的名称，请在名称前后添加 `，例如`testTable`。"
//表单信息
const tableInfo = ref({
	name: '',
	columnsInfo: [
		{
			name: '',
			type: 'TIMESTAMP',
			isLength: false,
			length: 8,
		}
	],
	tagsInfo: [
		{
			name: '',
			type: 'INT',
			isLength: false,
			length: 8,
		}
	]
})
//列或标签信息模板
const columnOrTagTemplate = {
	name: '',
	type: 'INT',
	isLength: false,
	length: 8,
}
/**
 * 表单验证相关内容
 */
/**
 * 验证表格名称
 * @param rule 校验规则
 * @param value 值
 * @param callback 回调方法
 */
const checkTableName = (rule, value, callback) => {
	//表名只能由字母、数字和下划线组成，且不能以数字开头。默认不区分大小写，
	//如果要创建区分大小写的名称，请在名称前后添加 `，例如`testTable`。
	let regex = /^(`[a-zA-Z_][a-zA-Z0-9_]*`|[a-zA-Z_][a-zA-Z0-9_]*)$/;
	if (regex.test(value)) {
		callback();
	} else {
		return callback(new Error(tableNameTooltipContent))
	}
}
const tableNameRules = ref({
	name: [
		{ required: true, message: "请输入表格名称", trrige: 'blur' },
		{ validator: checkTableName, trrige: 'blur' }
	]
})

const getInputSpan = (type) => {
	return TDENGINE_DATA_TYPES.find(item => item.name == type).isLength ? 8 : 14;
}

/**
 * 删除列
 * @param index 索引
 */
const deleteColumn = (index) => {
	tableInfo.value.columnsInfo.splice(index, 1);
}
/**
 * 增加列
 * @param index 指定索引
 */
const addColumn = (index) => {
	tableInfo.value.columnsInfo.splice(index + 1, 0, JSON.parse(JSON.stringify(columnOrTagTemplate)));
}

/**
 * 删除标签
 * @param index 指定索引
 */
const deleteTag = (index) => {
	tableInfo.value.tagsInfo.splice(index, 1);
}
/**
 * 添加标签
 * @param index 指定索引
 */
const addTag = (index) => {
	tableInfo.value.tagsInfo.splice(index + 1, 0, JSON.parse(JSON.stringify(columnOrTagTemplate)));
}

const updateRelevantData = (index, type) => {
	let data = null;
	//true 列 false 标签
	type ? data = tableInfo.value.columnsInfo : data = tableInfo.value.tagsInfo
	//要更新的列
	let target = data[index];
	let dataType = dataTypeOptions.value.find(item => item.name == target.type)
	target.isLength = dataType.isLength
}

/**
 * 暴露给父组件的内容
 */
defineExpose({
	tableInfo,
	childTableTags,
	formRef
})

</script>
<style lang="less" scoped>
.main-wrapper {
	width: 100%;
	height: 100%;

	.column-tag-config-wrapper {
		.max-width {
			width: 100%;
		}

		.row-class:not(:last-child) {
			margin-bottom: 12px;
		}

		.button {
			display: flex;
			justify-content: flex-end;
		}
	}
}
</style>